
package com.qdlc.p2p.manage.action;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;

import com.qdlc.p2p.biz.service.AccountLogService;
import com.qdlc.p2p.biz.service.AccountService;
import com.qdlc.p2p.biz.service.BorrowConfigService;
import com.qdlc.p2p.biz.service.BorrowRepaymentService;
import com.qdlc.p2p.biz.service.BorrowService;
import com.qdlc.p2p.biz.service.BorrowTenderService;
import com.qdlc.p2p.biz.service.ExperienceService;
import com.qdlc.p2p.biz.service.UserRedEnvelopeService;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.LogTplNid;
import com.qdlc.p2p.common.util.BigDecimalUtil;
import com.qdlc.p2p.dal.dto.BorrowConfig;
import com.qdlc.p2p.dal.model.ExperienceModel;
import com.qdlc.p2p.dal.model.UserRedEnvelopeModel;

@SuppressWarnings("rawtypes")
public class ReportAction extends BaseAction {
	
	@Resource
	private BorrowService borrowService;
	@Resource
	private BorrowConfigService borrowConfigService;
	@Resource
	private BorrowTenderService borrowTenderService;
	@Resource
	private BorrowRepaymentService borrowRepaymentService;
	@Resource
	private AccountService accountService;
	@Resource
	private AccountLogService accoutLogService;
	@Resource
	private UserRedEnvelopeService userRedEnvelopeService;
	@Resource
	private ExperienceService experienceService;
	
	private Map<String, Object> data;
	
	/**
	 * 投资人分析页面
	 * @return
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/tenderAnalysisPage")
	public String tenderAnalysisPage() throws Exception {
		getYearsForPage();
		
		return "tenderAnalysisPage";
	}
	/**
	 * 投资人基本信息
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/tenderBaseInfo")
	public void tenderBaseInfo() throws Exception {
		data = new HashMap<String, Object>();
		String date = paramString("date");
		int[] arr = borrowTenderService.getTenderInfoByDate(date);
		data.put("arr", arr);
		printJson(getStringOfJpaObj(data));
	}
	/**
	 * 投资人所在地分布
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/tenderAreaDistributed")
	public void tenderAreaDistributed() throws Exception {
		data = new HashMap<String, Object>();
		String date = paramString("date");
		Object[][] result = borrowTenderService.getTenderAreaDistributedByDate(date);
		data.put("provinces", result[0]);
		data.put("counts", result[1]);
		printJson(getStringOfJpaObj(data));
	}
	/**
	 * 历月累积投资人数
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/tenderAnalysis")
	public void tenderAnalysis() throws Exception {
		data = new HashMap<String, Object>();
		List<Integer> counts = new ArrayList<Integer>();
		List<String> dates = new ArrayList<String>();
		String year = paramString("year");
		for (int i = 1; i< 13; i++) {
			String date = year + (i > 9 ? "-" : "-0") + i;
			int acount = borrowTenderService.getTenderCountByDate(date);
			dates.add(date);
			counts.add(acount);
		}
		data.put("dates", dates.toArray());
		data.put("counts", counts.toArray());
		printJson(getStringOfJpaObj(data));
	}
	/**
	 * 当月投资金额或人数分布
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/tenderDistributed")
	public void tenderDistributed() throws Exception {
		data = new HashMap<String, Object>();
		String date = paramString("date");
		int type = paramInt("type");
		double[] distributed = borrowTenderService.getDistributedByTypeAndDate(type, date);
		data.put("distributed", distributed);
		printJson(getStringOfJpaObj(data));
	}
	
	/**
	 * 借款人分析页面
	 * @return
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/borrowAnalysisPage")
	public String borrowAnalysisPage() throws Exception {
		getYearsForPage();
		return "borrowAnalysisPage";
	}
	/**
	 * 借款人基本信息
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/borrowBaseInfo")
	public void borrowBaseInfo() throws Exception {
		data = new HashMap<String, Object>();
		String date = paramString("date");
		int[] arr = borrowService.getBorrowInfoByDate(date);
		data.put("arr", arr);
		printJson(getStringOfJpaObj(data));
	}
	/**
	 * 借款人所在地分布
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/borrowAreaDistributed")
	public void borrowAreaDistributed() throws Exception {
		data = new HashMap<String, Object>();
		String date = paramString("date");
		Object[][] result = borrowService.getBorrowAreaDistributedByDate(date);
		data.put("provinces", result[0]);
		data.put("counts", result[1]);
		printJson(getStringOfJpaObj(data));
	}
	/**
	 * 历月累积借款人数
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/borrowAnalysis")
	public void borrowAnalysis() throws Exception {
		data = new HashMap<String, Object>();
		List<Integer> counts = new ArrayList<Integer>();
		List<String> dates = new ArrayList<String>();
		String year = paramString("year");
		for (int i = 1; i< 13; i++) {
			String date = year + (i > 9 ? "-" : "-0") + i;
			int count = borrowService.getBorrowCountByDate(date);
			dates.add(date);
			counts.add(count);
		}
		data.put("dates", dates.toArray());
		data.put("counts", counts.toArray());
		printJson(getStringOfJpaObj(data));
	}
	/**
	 * 当月借款金额或人数分布
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/borrowDistributed")
	public void borrowDistributed() throws Exception {
		data = new HashMap<String, Object>();
		String date = paramString("date");
		int type = paramInt("type");
		double[] distributed = borrowService.getDistributedByTypeAndDate(type, date);
		data.put("distributed", distributed);
		printJson(getStringOfJpaObj(data));
	}
	/**
	 * 平台盈亏状况页面
	 * @return
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/profitAndLossAnalysisPage")
	public String profitAndLossAnalysisPage() throws Exception {
		getYearsForPage();
		return "profitAndLossAnalysisPage";
	}
	
	/**
	 * 平台收入
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/profit")
	public void profit() throws Exception {
		data = new HashMap<String, Object>();
		String year = paramString("year");
		// 根据年获取借款手续费
		double[] borrowManageFees = accoutLogService.amount(LogTplNid.BORROW_FEE, year);
		// 根据年获取利息管理费
		double[] interestManageFees = accoutLogService.amount(LogTplNid.INVESTOR_MANAGE_FEE, year);
		// 根据年获取债权管理费
		// double[] bondManageFees = accoutLogService.amount(Constant.BOND_SELL_MANAGEFEE, year);
		// 根据年获取债权利息管理费
		// double[] bondInterestManageFees = accoutLogService.amount(Constant.BOND_SELL_INTEREST_MANAGEFEE, year);
		// 根据年获取vip管理费
		double[] totalFee = new double[12];
		double borrowManageFee = 0;
		double interestManageFee = 0;
		/*double bondManageFee = 0;
		double bondInterestManageFee = 0;*/
		for (int i = 0; i < 12 ; i++) {
			totalFee[i] = BigDecimalUtil.add(borrowManageFees[i], interestManageFees[i]);
			borrowManageFee = BigDecimalUtil.add(borrowManageFees[i], borrowManageFee);
			interestManageFee = BigDecimalUtil.add(interestManageFees[i], interestManageFee);
			/*bondManageFee = BigDecimalUtil.add(bondManageFees[i], bondManageFee);
			bondInterestManageFee = BigDecimalUtil.add(bondInterestManageFees[i], bondInterestManageFee);*/
		}
		data.put("borrowManageFee", borrowManageFee);
		data.put("interestManageFee", interestManageFee);
		/*data.put("bondManageFee", bondManageFee);
		data.put("bondInterestManageFee", bondInterestManageFee);*/
		data.put("totalFee", totalFee);
		printJson(getStringOfJpaObj(data));
	}
	
	/**
	 * 平台支出
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/loss")
	public void loss() throws Exception {
		data = new HashMap<String, Object>();
		String year = paramString("year");
		// 根据年获取平台垫付提现手续费
		double[] webAdvanCashFees = accountService.getCashFeeByYear(year);
		double[] userRedEnvelopeFees = userRedEnvelopeService.getUseRedEnvelopeSumByStatus(UserRedEnvelopeModel.USER_RED_ENVELOPE_STATUS_USE,year);
		// 根据年获取平台送出vip奖励金额
		double[] vipInterestFees = accoutLogService.amount(LogTplNid.VIP_UP_RATE_INTEREST_REPAY , year);
		// 根据年获取积分抽奖送出现金
		double[] scoreLotteryMoneys = accoutLogService.amount(LogTplNid.SCORE_LOTTERY_MONEY, year);
		// 根据年获取体验券投标所支付本金
		double[] experienceCapital = experienceService.getExperienceByYear(ExperienceModel.EXPERIENCE_STATUS_USED, year);
		// 根据年获取加息券所支付利息
		double[] upRateCollections = accoutLogService.amount(LogTplNid.RATE_REPAY_INTEREST, year);
		//平台垫付充值手续费
		double[] webAdvanRechargeFees = accoutLogService.amount(LogTplNid.WEB_ADVAN_FEE,year);
		// 平台总支出
		double[] totalFee = new double[12];
		double userRedPacketFee = 0;
		double webAdvanCashFee = 0;
		double vipInterestFee = 0;
		double scoreLotteryMoney = 0;
		double upRateCollection = 0;
		double webAdvanRechargeFee = 0;
		double experienceMoney = 0;
		for (int i = 0; i < 12 ; i++) {
			totalFee[i] = BigDecimalUtil.add(userRedEnvelopeFees[i], webAdvanCashFees[i], vipInterestFees[i], scoreLotteryMoneys[i],  upRateCollections[i], webAdvanRechargeFees[i]);
			userRedPacketFee = BigDecimalUtil.add(userRedEnvelopeFees[i], userRedPacketFee);
			webAdvanCashFee = BigDecimalUtil.add(webAdvanCashFees[i], webAdvanCashFee);
			vipInterestFee = BigDecimalUtil.add(vipInterestFees[i], vipInterestFee);
			scoreLotteryMoney = BigDecimalUtil.add(scoreLotteryMoneys[i], scoreLotteryMoney);
			upRateCollection = BigDecimalUtil.add(upRateCollections[i], upRateCollection);
			webAdvanRechargeFee =  BigDecimalUtil.add(webAdvanRechargeFees[i], webAdvanRechargeFee);
			experienceMoney = BigDecimalUtil.add(experienceCapital[i], experienceMoney);
		}
		data.put("totalFee", totalFee);
		data.put("userRedPacketFee", userRedPacketFee);
		data.put("webAdvanCashFees", webAdvanCashFees);
		data.put("vipInterestFee", vipInterestFee);
		data.put("scoreLotteryMoney", scoreLotteryMoney);
		data.put("upRateCollection", upRateCollection);
		data.put("webAdvanRechargeFee", webAdvanRechargeFee);
		data.put("experienceMoney", experienceMoney);
		printJson(getStringOfJpaObj(data));
	}
	/**
	 * 平台盈亏状况
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/profitAndLossAnalysis")
	public void profitAndLossAnalysis() throws Exception {
		data = new HashMap<String, Object>();
		String year = paramString("year");
		// 根据年获取借款手续费
		double[] borrowManageFees = accoutLogService.amount(LogTplNid.BORROW_FEE, year);
		// 根据年获取利息管理费
		double[] interestManageFees = accoutLogService.amount(LogTplNid.INVESTOR_MANAGE_FEE, year);
		/*// 根据年获取债权管理费
		double[] bondManageFees = accoutLogService.getFeeByTypeAndYear(Constant.BOND_SELL_MANAGEFEE, year);
		// 根据年获取债权利息管理费
		double[] bondInterestManageFees = accoutLogService.getFeeByTypeAndYear(Constant.BOND_SELL_INTEREST_MANAGEFEE, year);
		*/
		
		// 根据年获取平台垫付提现手续费
		double[] webAdvanCashFees = accountService.getCashFeeByYear(year);
		double[] userRedEnvelopeFees = userRedEnvelopeService.getUseRedEnvelopeSumByStatus(UserRedEnvelopeModel.USER_RED_ENVELOPE_STATUS_USE,year);
		// 根据年获取平台送出vip奖励金额
		double[] vipInterestFees = accoutLogService.amount(LogTplNid.VIP_UP_RATE_INTEREST_REPAY , year);
		// 根据年获取积分抽奖送出现金
		double[] scoreLotteryMoneys = accoutLogService.amount(LogTplNid.SCORE_LOTTERY_MONEY, year);
		// 根据年获取体验券投标所支付利息
		/*double[] experienceCollections = accoutLogService.amount(Constant.EXPERIENCE_INTEREST_COLLECT, year);*/
		// 根据年获取加息券所支付利息
		double[] upRateCollections = accoutLogService.amount(LogTplNid.RATE_REPAY_INTEREST, year);
		//平台垫付充值手续费
		double[] webAdvanRechargeFees = accoutLogService.amount(LogTplNid.WEB_ADVAN_FEE,year);
		// 平台总收入
		double[] totalProfitFee = new double[12];
		// 平台总支出
		double[] totalLossFee = new double[12];
		for (int i = 0; i < 12 ; i++) {
			totalProfitFee[i] = BigDecimalUtil.add(borrowManageFees[i], interestManageFees[i]);
			totalLossFee[i] = BigDecimalUtil.add(webAdvanCashFees[i], userRedEnvelopeFees[i], vipInterestFees[i], scoreLotteryMoneys[i], upRateCollections[i], webAdvanRechargeFees[i]);
		}
		data.put("totalProfitFee", totalProfitFee);
		data.put("totalLossFee", totalLossFee);
		printJson(getStringOfJpaObj(data));
	}
	/**
	 * 交易规模分析页面
	 * @return
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/transactionSizeAnalysisPage")
	public String transactionSizeAnalysisPage() throws Exception {
		getYearsForPage();
		return "transactionSizeAnalysisPage";
	}
	/**
	 * 平台交易额或笔数
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/turnover")
	public void turnover() throws Exception {
		data = new HashMap<String, Object>();
		String date = paramString("date");
		int type = paramInt("type");
		getYearsForJOSN();
		double[][] turnover = borrowService.getTurnoverByTypeAndDate(type, date);
		data.put("turnover", turnover[0]);
		data.put("ratios", turnover[1]);
		if (date.length() == 7) {
			DateFormat sdf = new SimpleDateFormat("yyyy-MM");
			Date d = sdf.parse(date);
			Calendar c = Calendar.getInstance();
			c.setTime(d);
			int totalDay = c.getActualMaximum(Calendar.DATE);
			String[] days = new String[totalDay];
			for (int i = 0; i< totalDay; i++) {
				days[i] = (i + 1) + "日";
			}
			data.put("years", days);
		}
		printJson(getStringOfJpaObj(data));
	}
	/**
	 * 平台累计借款人
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/cumulativeBorrow")
	public void cumulativeBorrow() throws Exception {
		data = new HashMap<String, Object>();
		getYearsForJOSN();
		String date = paramString("date");
		double[] cumulativeBorrow = borrowService.getCumulativeBorrowByDate(date);
		data.put("cumulativeBorrow", cumulativeBorrow);
		printJson(getStringOfJpaObj(data));
	}
	/**
	 * 平台累计投资人
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/cumulativeTender")
	public void cumulativeTender() throws Exception {
		data = new HashMap<String, Object>();
		getYearsForJOSN();
		String date = paramString("date");
		double[] cumulativeTender = borrowTenderService.getCumulativeTenderByDate(date);
		data.put("cumulativeTender", cumulativeTender);
		printJson(getStringOfJpaObj(data));
	}
	
	/**
	 * 借款产品分析页面
	 * @return
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/borrowProductAnalysisPage")
	public String borrowProductAnalysisPage() throws Exception {
		List<BorrowConfig> list = borrowConfigService.findAll();
		request.setAttribute("list", list);
		getYearsForPage();
		return "borrowProductAnalysisPage";
	}
	
	/**
	 * 当月借款产品金额或人数分布
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/borrowProductDistributed")
	public void borrowProductDistributed() throws Exception {
		data = new HashMap<String, Object>();
		String date = paramString("date");
		int type = paramInt("type");
		double[] distributed = borrowService.getProductDistributedByTypeAndDate(type, date);
		data.put("distributed", distributed);
		List<BorrowConfig> list = borrowConfigService.findAll();
		String[] typeNames = new String[list.size()];
		for (int i = 0;i < list.size(); i++) {
			typeNames[i] = list.get(i).getName();
		}
		data.put("typeNames", typeNames);
		printJson(getStringOfJpaObj(data));
	}
	/**
	 * 标成交笔数或金额及同比值
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/borrowInfoAnalysis")
	public void borrowInfoAnalysis() throws Exception {
		data = new HashMap<String, Object>();
		List<Double> counts = new ArrayList<Double>();
		List<Double> ratios = new ArrayList<Double>();
		List<String> dates = new ArrayList<String>();
		int type = paramInt("type");
		int borrowType = paramInt("borrowType");
		String year = paramString("year");
		for (int i = 1; i< 13; i++) {
			String date = year + (i > 9 ? "-" : "-0") + i;
			double[] result = borrowService.getDealCountByTypeAndBorrowTypeAndDate(type, borrowType, date);
			dates.add(date);
			counts.add(result[0]);
			ratios.add(result[1]);
		}
		data.put("dates", dates);
		data.put("counts", counts);
		data.put("ratios", ratios);
		printJson(getStringOfJpaObj(data));
	}
	/**
	 * 标成交笔数或金额占比
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/borrowInfoRatios")
	public void borrowInfoRatios() throws Exception {
		data = new HashMap<String, Object>();
		int type = paramInt("type");
		String date = paramString("date");
		double[] ratios = borrowService.getDealRatiosByTypeAndDate(type, date);
		List<BorrowConfig> list = borrowConfigService.findAll();
		String[] typeNames = new String[list.size()];
		for (int i = 0;i < list.size(); i++) {
			typeNames[i] = list.get(i).getName();
		}
		data.put("typeNames", typeNames);
		data.put("ratios", ratios);
		printJson(getStringOfJpaObj(data));
	}
	/**
	 * 风险控制分析页面
	 * @return
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/riskAnalysisPage")
	public String riskAnalysisPage() throws Exception {
		getYearsForPage();
		return "riskAnalysisPage";
	}
	/**
	 * 逾期人数或金额分析
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/overdueAnalysis")
	public void overdueAnalysis() throws Exception {
		data = new HashMap<String, Object>();
		List<Double> counts = new ArrayList<Double>();
		List<String> dates = new ArrayList<String>();
		int type = paramInt("type");
		int year = paramInt("year");
		if (type == 0) {
			List<Double> sums = new ArrayList<Double>();
			for (int i = 1; i< 13; i++) {
				String date = year + (i > 9 ? "-" : "-0") + i;
				double[] results = borrowRepaymentService.getOverdueByDate(date);
				counts.add(results[0]);
				sums.add(results[1]);
				dates.add(date);
			}
			data.put("sums", sums);
		} else {
			List<Double> ratios = new ArrayList<Double>();
			for (int i = 1; i< 13; i++) {
				String month = (i > 9 ? "-" : "-0") + i;
				String date = year + month;
				double result = borrowRepaymentService.getOverdueByTypeAndDate(type, date);
				double prev = borrowRepaymentService.getOverdueByTypeAndDate(type, (year - 1) + month);
				counts.add(result);
				dates.add(date);
				double ratio = 0;
				if (prev != 0) {
					ratio = BigDecimalUtil.div(BigDecimalUtil.sub(result, prev), prev);
				} 
				ratios.add(ratio);
				prev = result;
			}
			data.put("ratios", ratios);
		}
		data.put("dates", dates);
		data.put("counts", counts);
		printJson(getStringOfJpaObj(data));
	}
	/**
	 * 逾期借款人基本信息
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/borrowOverdueBaseInfo")
	public void borrowOverdueBaseInfo() throws Exception {
		data = new HashMap<String, Object>();
		String date = paramString("date");
		int[] arr = borrowRepaymentService.getOverdueInfoByDate(date);
		data.put("arr", arr);
		printJson(getStringOfJpaObj(data));
	}
	/**
	 * 投资人所在地分布
	 * @throws Exception
	 */
	@Action("/modules/operatingStatistics/borrowOverdueAreaDistributed")
	public void borrowOverdueAreaDistributed() throws Exception {
		data = new HashMap<String, Object>();
		String date = paramString("date");
		Object[][] result = borrowRepaymentService.getOverdueAreaDistributedByDate(date);
		data.put("provinces", result[0]);
		data.put("counts", result[1]);
		printJson(getStringOfJpaObj(data));
	}
	/**
	 * 封装近五年年数数组给JSON
	 */
	private void getYearsForJOSN() {
		int[] years = new int[5];
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		for (int i = 0; i < 5; i++) {
			years[i] = year - 4 + i;
		}
		data.put("years", years);
	}
	/**
	 * 封装近五年年数集合给页面
	 */
	private void getYearsForPage() {
		List<Integer> years = new ArrayList<Integer>();
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		for (int i = year - 4; i <= year; i++) {
			years.add(i);
		}
		int currentMonth = c.get(Calendar.MONTH)+1;
		request.setAttribute("currentYear", year);
		request.setAttribute("years", years);
		request.setAttribute("currentMonth", currentMonth);
	}
	
}
